package com.power.ding.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;
import com.power.ding.runner.jobs.MessageJob;

@RestController
public class ThreadController {
	@RequestMapping("/getStatus")
	public JSONObject getStatus(String name) {
		JSONObject re=new JSONObject();
		Thread thread=getThreadByName(name);
		if(thread!=null) {
			re.put("id", thread.getId());
			re.put("name", thread.getName());
			re.put("priority", thread.getPriority());
			re.put("state", thread.getState());
//			state的意义
//			NEW：线程刚被创建，还没有调用start()方法；
//			RUNNABLE：线程正在Java虚拟机中执行，也可能在等待操作系统资源，如处理器；
//			BLOCKED：线程阻塞于监视器锁，等待其他线程释放锁；
//			WAITING：线程在等待其他线程执行特定操作；
//			TIMED_WAITING：线程在指定的等待时间内等待另一个线程执行特定操作；
//			TERMINATED：线程已执行完毕。
			
			re.put("isAlive", thread.isAlive()); //是否处于活动状态
			re.put("isDaemon", thread.isDaemon()); //是否是后台守护线程
			re.put("isInterrupted", thread.isInterrupted()); //是否被中断
		}
		
		return re;
	}
	
	@RequestMapping("/stop")
	public JSONObject stop(String name) {
		JSONObject re=new JSONObject();
		boolean succ=false;
		Thread thread=getThreadByName(name);
		if(thread!=null) {
			thread.stop();
			succ=true;
		}

		re.put("stop", succ);
		return re;
	}
	
	@RequestMapping("/start")
	public JSONObject start(String name) {
		JSONObject re=new JSONObject();
		if(name.equals("DingMessageJob")) {
			new Thread(MessageJob.getInstance(), "DingMessageJob").start();
		}
		return re;
	}
	
	public static Thread getThreadByName(String threadName) {
		ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();
        Thread[] threads = new Thread[threadGroup.activeCount()];
        int actualSize = threadGroup.enumerate(threads);
        for (int i = 0; i < actualSize; i++) {
            if (threads[i].getName().equals(threadName)) {
                return threads[i];
            }
        }
        return null;
    }
}
